<?php
/******************************************************************************
 *
 *    OpenZoowa - Web App to manage events
 *    Copyright (C) 2008 Jesus Ruiz-Ayucar
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/
   if (!defined('ZOOWA')) {
      include_once('../../config.php');
   }

   class Util {
      public static function getServerName() {
         if($_SERVER['SERVER_NAME']) {
            return $_SERVER['SERVER_NAME'];
         } else {
            return $GLOBALS['domain'];
         }
      }

      public static function startupDataBase() {
         global $db;
         if(!isset($db)) {
            include_once (utilitiespath . 'ezSQL/ez_sql_core.php');
            include_once (utilitiespath . 'ezSQL/ez_sql_mysql.php');
            $db = new ezSQL_mysql($GLOBALS['db_user'], $GLOBALS['db_password'], $GLOBALS['db_name'], $GLOBALS['db_server']);
            $db->query("SET NAMES 'utf8'");
         }
      }

      public static function startupTemplate($controller = '', $action = '') {
         global $lang, $current_user;
         require_once(utilitiespath . 'smarty/Smarty.class.php');
         $smarty = new Smarty();
         $smarty->template_dir = themespath.'/'.$GLOBALS['theme'].'/';
         $smarty->compile_dir  = utilitiespath.'smarty/templates_c/';
         $smarty->config_dir   = utilitiespath.'smarty/configs/';
         $smarty->cache_dir    = utilitiespath.'smarty/cache/';
         $smarty->assign('lang',$lang);
         $smarty->assign('controller',$controller);
         $smarty->assign('action',$action);
         //$id = $current_user->getId();
         //if(isset($id)) {
            $smarty->assign('user',$current_user);
         //}
         return $smarty;
      }

      public static function setConfig($basepath) {
         global $db;

         // Definimos directorios
         define("basepath", $basepath);
         define("avatarpath", basepath . '/z-content/img/avatars/');
         define("libspath", basepath .'/z-include/');
         define("modelspath", basepath .'/z-include/models/');
         define("controllerspath", basepath .'/z-include/controllers/');
         define("themespath", basepath .'/z-content/themes/');
         define("utilitiespath", basepath.'/z-include/utilities/');

         date_default_timezone_set("Europe/Madrid");
         $GLOBALS['now']		= time();
         $GLOBALS['version']	= '0.0.1';
         $GLOBALS['now']		= time();
         $GLOBALS['version']	= '0.0.1';
         $GLOBALS['cookie_name']	= 'openzoowa';



         // Extraemos y asignamos los parámetros de configuración globales
         self::startupDataBase();
         $SQL = 'SELECT name, value FROM '.$GLOBALS['db_pre'].'config';
         $result = $db->get_results($SQL);

         if (isset($result)) {
            foreach($result as $config) {
               $GLOBALS[$config->name] = $config->value;
            }

            // Incluimos el fichero con el idioma
            global $lang;
            include_once(basepath . '/z-content/languages/'.$GLOBALS['language'].'.php');
            require_once (modelspath . 'user.php');

            Util::startupDataBase();

            // Cada vez que se incluye esta clase, creamos un usuario
            global $current_user;
            $current_user = new User();
            $current_user->setUser();
         }
      }

      public static function addErrorMsg(&$errors, $msg) {
         if(isset($msg)) {
            $errors[] = $msg;
         }
      }

      public static function clean_name($string) {
         $conv = array(
            "¢" => "c", "£" => "L", "¤" => "x",
            "¥" => "Y", "€" => "E", "§" => "S",
            "ª" => "a", "®" => "r", "²" => "2",
            "³" => "3", "µ" => "u", "¹" => "1",
            "×" => "x", "À" => "A", "Á" => "A",
            "Â" => "A", "Ã" => "A", "Ä" => "A",
            "Å" => "A", "Æ" => "AE","Ç" => "C",
            "È" => "E", "É" => "E", "Ê" => "E",
            "Ë" => "E", "Ì" => "I", "Í" => "I",
            "Î" => "I", "Ï" => "I", "Ð" => "D",
            "Ñ" => "N", "Ò" => "O", "Ó" => "O",
            "Ô" => "O", "Õ" => "O", "Ö" => "O",
            "Ø" => "O", "Ù" => "U", "Ú" => "U",
            "Û" => "U", "Ü" => "U", "Ý" => "Y",
            "Þ" => "P", "ß" => "B", "à" => "a",
            "á" => "a", "â" => "a", "ã" => "a",
            "ä" => "a", "å" => "a", "æ" => "ae",
            "ç" => "c", "è" => "e", "é" => "e",
            "ê" => "e", "ë" => "e", "ì" => "i",
            "í" => "i", "î" => "i", "ï" => "i",
            "ð" => "d", "ñ" => "n", "ò" => "o",
            "ó" => "o", "ô" => "o", "õ" => "o",
            "ö" => "o", "ø" => "o", "ù" => "u",
            "ú" => "u", "û" => "u", "ü" => "u",
            "ý" => "y", "þ" => "p", "ÿ" => "y");

         // Quito espacios de los lados
         $string = trim($string);
         // Quito barras
         $string = stripslashes($string);
         // Paso a minúsculas
         $string = strtolower($string);
         // Quito tags
         $string = preg_replace("/&[^\s;]+;/","", $string);
         // Sustituyo lo sustituible :P
         $string = strtr($string, $conv);
         // Todo lo que no sean letras, numeros, guiones o espacios lo borro
         $string = preg_replace("/[^a-z0-9\-_ ]/","", $string);
         // Sustituyo los espacios y guiones bajo por guiones
         $string = preg_replace("/[ _]/","-", $string);
         // Cuando haya uno o más guiones lo dejo en solo uno
         $string = preg_replace("/[\-]+/","-", $string);
         return $string;
      }

      public static function validateUrl($url) {
         return preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_\~]+$/i",$url);
      }

      public static function is_numeric($var) {
         return preg_match ("/^([0-9.,-]+)$/", $var);
      }

      public static function get_link($controller = null, $action = null, $id = null, $params = null) {
         $url = $GLOBALS['domain'].$GLOBALS['base_url'];
         if (!$GLOBALS['fancy_url']) {
            $url .= 'index.php';
            $par = false;
            if (isset($controller)) {
               $par = true;
               $url .= '?c='.$controller;
               if (isset($action)) {
                  $url .= '&a='.$action;
                  if (isset($id)) {
                     $url .= '&id='.$id;
                  }
               }
            }
         } else {
            if (isset($controller)) {
               $url .= $controller;
               if (isset($action)) {
                  $url .= '/'.$action;
                  if (isset($id)) {
                     $url .= '/'.$id;
                  }
               }
            }
         }

         if (isset($params)) {
            foreach($params as $name => $value) {
               if($par) {
                  $url .= '&';
               } else {
                  $par = true;
                  $url .= '?';
               }
               $url .= urlencode($name).'='.urlencode($value);
            }
         }

         return $url;
      }

      public static function format_date($date) {
         $date = explode('-', $date);

         if(!empty($date[0]) &&
            !empty($date[1]) &&
            !empty($date[2]) &&
            checkdate($date[1], $date[2],$date[0]))
         {
            global $lang;
            $date_ts = mktime(0,0,0,$date[1],$date[2],$date[0]);
            return date($lang['date_format'], $date_ts);
         }
      }

      public static function days_of_month($month, $year) {
         switch($month) {
            case '1': case '01':
            case '3': case '03':
            case '5': case '05':
            case '7': case '07':
            case '8': case '08':
            case '10':
            case '12':
               return 31;
            case '4': case '04':
            case '6': case '06':
            case '9': case '09':
            case '11':
               return 30;
            case '2':
               if(date('L', mktime('00','00','00','01','01',$year))) {
                  return 29;
               } else {
                  return 28;
               }
         }
      }
   }
?>